package com.dddframework.security.domain.auth.component;

import cn.hutool.http.HttpStatus;
import com.dddframework.core.contract.R;
import com.dddframework.core.utils.JsonKit;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 根据 AuthenticationException不同细化异常处理
 *
 * @author zhouzx
 */
@Slf4j
public class ResourceAuthExceptionEntryPoint implements AuthenticationEntryPoint {

    @Override
    @SneakyThrows
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        R<String> result = new R<>();
        result.setCode(1);
        if (authException != null) {
            result.setMsg(authException.getMessage());
            result.setData(authException.getMessage());
            if (authException instanceof InsufficientAuthenticationException || authException instanceof CredentialsExpiredException) {
                result.setMsg("证书过期请重新登录");
                result.setData("invalid_token");
            }
        }
        response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
        response.getWriter().append(JsonKit.DEFAULT_OBJECT_MAPPER.writeValueAsString(result));
    }
}
